<template>
  <el-dialog
    title="硬件编辑"
    v-model="visible"
    top="10vh"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataFormRules"
      label-position="right"
      label-width="120px"
      v-loading="loading"
    >
    <el-form-item label="硬件名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入硬件名称"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="number">
        <el-input-number
          v-model.number="dataForm.number"
          :min="1"
          :step="1"
          :precision="0"
          step-strictly
        ></el-input-number>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerId">
        <KSelect
          ref="selectRef"
          labelName="name"
          valueName="id"
          placeholder="请选择客户"
          :selectValue="dataForm.customerId"
          :total="customerAllList.data.total"
          :dataList="customerAllList.data.list"
          :selectCallback="getCustomerInfo"
        ></KSelect>
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierId">
        <KSelect
          ref="selectSupplierRef"
          labelName="name"
          valueName="id"
          placeholder="请选择供应商"
          :selectValue="dataForm.supplierId"
          :total="supplierAllList.data.total"
          :dataList="supplierAllList.data.list"
          :selectCallback="getSupplierInfo"
        ></KSelect>
      </el-form-item>
      <el-form-item label="客户手机号" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="请输入客户手机号"></el-input>
      </el-form-item>
      <el-form-item label="收货地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="请输入收货地址"></el-input>
      </el-form-item>
      <el-form-item label="发货日期" prop="orderDate">
        <el-date-picker
          v-model="dataForm.orderDate"
          type="datetime"
          placeholder="请选择发货时间"
        />
      </el-form-item>
      <el-form-item label="技术负责人" prop="technologyChargePerson">
        <el-input v-model="dataForm.technologyChargePerson" placeholder="请输入技术负责人"></el-input>
      </el-form-item>
      <el-form-item label="采购负责人" prop="purchaseChargePerson">
        <el-input v-model="dataForm.purchaseChargePerson" placeholder="请输入采购负责人"></el-input>
      </el-form-item>
      <el-form-item label="审核人" prop="examinePerson">
        <el-input v-model="dataForm.examinePerson" placeholder="请输入审核人"></el-input>
      </el-form-item>
      <el-form-item label="订单类型" prop="type">
        <el-select v-model="dataForm.type" disabled clearable style="width: 180px" placeholder="请选择订单类型">
          <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label" :value="item.value">
            <k-badge :type="item.type" :content="item.label"></k-badge>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="快递公司" prop="courierCompany">
        <el-select v-model="dataForm.courierCompany" filterable clearable style="width: 180px" placeholder="请选择快递公司" @change="getCourierEvent">
          <el-option v-for="item in expressList" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="快递单号" prop="courierNumber">
        <el-input v-model="dataForm.courierNumber" placeholder="请输入快递单号"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="dataForm.remark" placeholder="请输入备注"></el-input>
      </el-form-item>
      <el-form-item label="审核备注" prop="auditRemark" v-if="dataForm.status !== 2">
        <el-input type="textarea" disabled v-model="dataForm.auditRemark" placeholder="请输入审核备注"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'
import { validPhone, validEmail } from '@/utils/validate'
import type { ListResultData, Pagination } from '@/api/base'
import {
  getCustomerList,
  getSupplierList,
  type QueryCustomerList,
  type CustomerApiResult,
  type QuerySupplierList,
  type SupplierApiResult
} from '@/api/equipmentAdmin'

import { getEquipmentInfo, updateEquipment, type ICreateOrUpdateEquipment } from '@/api/equipment'
import { ElMessage } from 'element-plus'
import { getExpressList } from '@/utils/express'
import KSelect from '@/components/Select/index.vue'

import { useApiLock } from '_hooks'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  currId: {
    type: String,
    required: true,
    default: ''
  },
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const visible = ref<boolean>(false)

const handleClose = () => {
  emit(UPDATE_MODEL_EVENT, false)
}

const orderTypeList = ref<Array<any>>([{
  label: '退货',
  value: 'return',
  type: 'danger'
},
{
  label: '换货',
  value: 'barter',
  type: 'warning'
},
{
  label: '发货',
  value: 'deliver',
  type: 'primary'
}])

const defaultForm = {
  id: '',
  name: '',
  number: 1,
  customerId: '',
  customerName: '',
  supplierId: '',
  supplierName: '',
  phone: '',
  address: '',
  orderDate: '',
  technologyChargePerson: '',
  purchaseChargePerson: '',
  examinePerson: '',
  courierCompany: '',
  courierCompanyName: '',
  courierNumber: '',
  type: '',
  remark: '',
  auditRemark: '',
  status: 2
}
// 表单逻辑
const dataForm = ref<ICreateOrUpdateEquipment>({ ...defaultForm })

const validPhoneNum = (rule: any, value: string, callback: any) => {
  if (validPhone(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的手机号'))
  }
}

const dataFormRules = {
  name: [{ required: true, message: '请输入硬件名称', trigger: 'blur' }],
  customerId: [{ required: true, message: '请选择客户', trigger: 'blur' }],
  supplierId: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入客户手机号', trigger: 'blur' },
    { validator: validPhoneNum, trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
  ],
  type: [{ required: true, message: '请选择订单类型', trigger: 'blur' }],
}
const loading = ref<boolean>(false)
// 查询硬件详情
const getEquipmentInfoApi = async (currId: string) => {
  loading.value = true
  const res = await getEquipmentInfo(currId)
  loading.value = false
  if (res?.code === 200) {
    dataForm.value = res.data as ICreateOrUpdateEquipment
  }
}

const expressList = ref<Array<any>>([])

watch(
  () => props.modelValue,
  async () => {
    visible.value = props.modelValue
    if (props.modelValue && props.currId) {
      expressList.value = getExpressList()
      getEquipmentInfoApi(props.currId)
      getCustomerListApi({ page: 1, size: 20 })
      getSupplierListApi({ page: 1, size: 20 })
    }
  }
)

const dataFormRef = ref()
const updateOrCreate = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const res = await updateEquipment(dataForm.value)
      loading.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '更新成功' })
        emit('change')
        handleClose()
      } else {
        ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
      }
    }
  })
}

export interface IkSelect<T> {
  data: {
    list: Array<T>
    total?: number
  }
  pageSize?: number
}

const customerAllList = ref<IkSelect<CustomerApiResult>>({
  data: { list: [], total: 0 },
  pageSize: 20,
})
const getCustomerListApi = async ({ page, size }: Pagination) => {
  const res = await await useApiLock(() => getCustomerList({ page, size } as QueryCustomerList), 500)
  if (res?.code === 200) {
    const data = res.data as ListResultData<CustomerApiResult>
    customerAllList.value.data = data
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}

const getCustomerInfo = (customerInfo: CustomerApiResult) => {
  dataForm.value.address = customerInfo.address
  dataForm.value.phone = customerInfo.phone
  dataForm.value.customerName = customerInfo.name
  dataForm.value.customerId = customerInfo.id
}

const supplierAllList = ref<IkSelect<CustomerApiResult>>({
  data: { list: [], total: 0 },
  pageSize: 20,
})
const getSupplierListApi = async ({ page, size }: Pagination) => {
  const res = await await useApiLock(() => getSupplierList({ page, size } as QuerySupplierList), 500)
  if (res?.code === 200) {
    const data = res.data as ListResultData<SupplierApiResult>
      supplierAllList.value.data = data
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}

const getSupplierInfo = (customerInfo: CustomerApiResult) => {
  dataForm.value.supplierName = customerInfo.name
  dataForm.value.supplierId = customerInfo.id
}

const getCourierEvent = (code: string) => {
  dataForm.value.courierCompanyName = expressList.value.find((item: any) => item.code === code)?.name
}
</script>
